package cn.iocoder.yudao.module.system.api.extend;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 岗位 API 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class ExtendApiImpl implements ExtendApi {

    @Value("${extend.domain}")
    private String domain;

    /**
     * 自定义域名
     *
     * @param domain
     */
    @Override
    public void setDomain(String domain) {
        if (SpringUtil.getProperty("spring.profiles.active").equals("local")) {
            this.domain = domain;
        }
    }

    @Override
    public JSONObject request(String path, String params) {
        HttpResponse httpResponse = HttpUtil.createPost(this.domain + path)
                .body(params)
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .execute();
        String result = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (httpResponse.isOk()) {
            if (ObjectUtil.equal(0, jsonObject.getInt("code"))) {
                return jsonObject.getJSONObject("data");
            } else {
                throw exception(EXTEND_ERROR, jsonObject.getStr("msg"));
            }
        } else {
            throw exception(EXTEND_ERROR, "API请求失败");
        }

    }

    @Override
    public JSONObject requestCustomUrl(String path, String params,String key) {
        try {
            HttpResponse httpResponse = HttpUtil.createPost(path)
                    .body(params)
                    .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                    .header(Header.AUTHORIZATION, key)
                    .execute();
            String result = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (httpResponse.isOk()) {
                if (ObjectUtil.equal(0, jsonObject.getInt("code"))) {
                    return jsonObject.getJSONObject("data");
                } else {
                    throw exception(EXTEND_ERROR, jsonObject.getStr("msg"));
                }
            } else {
                throw exception(EXTEND_ERROR, "API请求失败");
            }
        } catch (Exception e) {
            return null;
        }
    }
    @Override
    public JSONObject requestGet(String path, String params) {
        HttpResponse httpResponse = HttpUtil.createGet(this.domain + path)
                .body(params)
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .execute();
        String result = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (httpResponse.isOk()) {
            if (ObjectUtil.equal(0, jsonObject.getInt("code"))) {
                return jsonObject.getJSONObject("data");
            } else {
                throw exception(EXTEND_ERROR, jsonObject.getStr("msg"));
            }
        } else {
            throw exception(EXTEND_ERROR, "API请求失败");
        }

    }
    @Override
    public JSONObject requestCustomTokenGet(String path, String token) {
        HttpResponse httpResponse = HttpUtil.createGet( path)
                .body("")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .header(Header.AUTHORIZATION, token)
                .execute();
        String result = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (httpResponse.isOk()) {
            if (ObjectUtil.equal(200, jsonObject.getInt("code"))) {
                return jsonObject;
            } else {
                throw exception(EXTEND_ERROR, jsonObject.getStr("msg"));
            }
        } else {
            throw exception(EXTEND_ERROR, "API请求失败");
        }

    }

    /**
     * 文字转拼音
     *
     * @param str
     * @return
     */
    @Override
    public String pinyin(String str) {
        Map<String, String> params = new HashMap<String, String>() {{
            put("str", str);
        }};
        JSONObject result = this.request("/index/pinyin", JSONUtil.toJsonStr(params));
        return result.getStr("pinyin");
    }

    /**
     * 初始化flow缓存
     *
     * @param flowId
     */
    @Override
    public void initMatchCache(Long flowId) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("flowId", flowId);
        }};
        this.request("/ivr/initMatchCache", JSONUtil.toJsonStr(params));
    }

    /**
     * 清理flow缓存
     *
     * @param flowId
     */
    @Override
    public void clearMatchCache(Long flowId) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("flowId", flowId);
        }};
        this.request("/ivr/clearMatchCache", JSONUtil.toJsonStr(params));
    }

    /**
     * 新增知识库缓存
     *
     * @param id
     */
    @Override
    public void addKnowledgeCache(Long id) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("id", id);
        }};
        this.request("/ivr/addKnowledgeCache", JSONUtil.toJsonStr(params));
    }

    @Override
    public JSONObject monitor(List<String> agentIdList) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("agentIdList", agentIdList);
        }};
       return this.request("/agent/monitor", JSONUtil.toJsonStr(params));
    }
}
